from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from libs.al_pay import alipay
from utils.common_logger import logger
from .serializer import OrderPaySerializer
from .models import Order
from utils.common_response import APIResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
import json


class OrderPayView(GenericViewSet):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    serializer_class = OrderPaySerializer

    def create(self, request, *args, **kwargs):
        ser = self.get_serializer(data=request.data, context={'request': request})
        ser.is_valid(raise_exception=True)
        ser.save()
        pay_url = ser.context.get('pay_url')
        return APIResponse(pay_url=pay_url)


class OrderSuccessView(APIView):
    def get(self, request, *args, **kwargs):
        # 给咱们前端用
        # 1 取出订单号
        out_trade_no = request.query_params.get('out_trade_no')
        # 2 去数据库查询
        order = Order.objects.filter(out_trade_no=out_trade_no, order_status=1).first()
        if order:  # 说明支付宝的post回调回来了，修改了订单状态
            return APIResponse(msg='支付成功，请去学习把')
        else:
            return APIResponse(code=101, msg='暂未收到您的付款，请稍后刷新再试')

    def post(self, request, *args, **kwargs):
        result_data = request.data.dict()  # 把request.data  ---> 转成字典格式
        logger.error(f'支付宝回调的数据：{json.dumps(result_data)}')
        try:
            out_trade_no = result_data.get('out_trade_no')
            trade_no = result_data.get('trade_no')
            signature = result_data.pop('sign')
            pay_time = result_data.get('notify_time', '2024-06-01')
            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1, trade_no=trade_no,
                                                                       pay_time=pay_time)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        finally:
            logger.error(f'---------支付宝回调的数据：{json.dumps(result_data)}')
        return Response('failed')
